package org.frog.sgs.client;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.frog.sgs.io.SgsMsg;

/**
 * @author duanxiangqi
 * @date 2012-10-20
 */
public class ClientIoHandler implements IoHandler {

	private static Logger logger = Logger.getLogger(ClientIoHandler.class);

	private SgsClient client;

	public void sessionCreated(IoSession session) throws Exception {}

	public void messageReceived(IoSession session, Object obj) throws Exception {
		ClientMsgDispatcher.instance.dispatch(session, (SgsMsg) obj, client.getInstance());
	}

	public void messageSent(IoSession session, Object obj) throws Exception {}

	public void sessionClosed(IoSession session) throws Exception {
		logger.info("sessionClosed:" + session.getRemoteAddress());
		client.stop();
	}

	public void exceptionCaught(IoSession session, Throwable throwable) throws Exception {
		logger.error("exceptionCaught " + throwable);
		throwable.printStackTrace();
	}

	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {}

	public void sessionOpened(IoSession session) throws Exception {}

	public SgsClient getClient() {
		return client;
	}

	public void setClient(SgsClient client) {
		this.client = client;
	}
}
